/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gidoo.websites.example;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.gidoo.cms.jcr.JcrHelper;
import org.gidoo.cms.login.GidooCMSSession;

/**
 *
 * @author thomas
 */
public class MenuPanel extends Panel 
{
  public MenuPanel(String id, List items)
  {
    super(id);
    
    ListView lsvMenu = new ListView("lsvMenu", items) {

      @Override
      protected void populateItem(ListItem item)
      {
        Object o = item.getModelObject();
        
        if(o == null)
        {
          throw new NullPointerException();
        }
        
        if(o instanceof List)
        {
          MenuPanel nestedList = new MenuPanel("nestedList", (List) o);
          nestedList.setRenderBodyOnly(true);
          item.add(nestedList);
          
          WebMarkupContainer row = new WebMarkupContainer("row");
          row.setVisible(false);
          item.add(row);
          item.setRenderBodyOnly(true);
            
        }
        else if(o instanceof Node)
        {
          try
          {
            Node n = (Node) o;
            WebMarkupContainer nestedList = new WebMarkupContainer("nestedList");
            item.add(nestedList);
            nestedList.setVisible(false);

            WebMarkupContainer row = new WebMarkupContainer("row");

            Node root = ((GidooCMSSession) getSession()).getJcrRootNode();
            
            String url = "/gidooCMS/" + ((App) getApplication()).getCMSPath() + "/"
              + JcrHelper.getPartialURLForNode(root, n);
            
            AbstractLink link = new AbstractLink("link") {};
            
            link.add(new AttributeModifier("href", new Model(url)));

            Label label = new Label("label", new Model(n.getProperty("cms:title").getString()));
            link.add(label);
            label.setRenderBodyOnly(true);

            row.add(link);
            item.add(row);
            item.setRenderBodyOnly(true);
          }
          catch(RepositoryException ex)
          {
            Logger.getLogger(MenuPanel.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
        else
        {
          throw(new UnsupportedOperationException(
            "You need to add lists of lists and folders to the MenuPanel. Object " +
            "was of type" + o.getClass().getName()));
        }
      }
    };
    
    add(lsvMenu);
    
  }

}
